package com.sqfw.project.zj.service;


import com.alibaba.fastjson2.JSONObject;
import com.sqfw.common.exception.base.BaseException;
import com.sqfw.common.utils.DateUtils;
import com.sqfw.project.utils.HttpClientUtils;
import com.sqfw.project.wp.service.TSMSSendLogService;
import com.sqfw.project.zj.domain.ZjRecord;
import dm.jdbc.driver.DmDriver;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时把语音系统的录音数据同步过来
 */
//@Component
public class ScheduledTask {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);

    @Value("${yuyindb.url}")
    private String url;

    @Value("${yuyindb.user}")
    private String user;

    @Value("${yuyindb.psd}")
    private String psd;

    @Value("${zj-record.record-file-path-prefix}")
    private String recordFilePathPrefix;

    @Value("${server.port}")
    private String port;

    @Value("${smgp.checkSmsUrl}")
    private String checkSmsUrl;

    public ScheduledTask() {
    }

    @Autowired
    private IZjRecordService iZjRecordService;

    @Autowired
    private TSMSSendLogService tsmsSendLogService;

    /**
     * 每天凌晨1点开始
     */
   // @Scheduled(cron = "0 0 1 * * ? ")
    public void syncRecordData() throws SQLException, ClassNotFoundException {

        if (!"8091".equals(port)) {
            return;
        }
        // 本地录音表中CREATE_TIME 最近时间
        ZjRecord lastRecord = iZjRecordService.selectLastRecord();
        String lastRecordDate = lastRecord == null ? "1970-1-1 00:00:00"
                : DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", lastRecord.getCreateTime());
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 查询语音系统 db_record_event时间大于lastRecordDate的
        Connection conn = DriverManager.getConnection(url, user, psd);

        String schema = conn.getSchema();
        String sql = "select * from " + schema + ".db_record_event where eventTime > '" + lastRecordDate + "'"+"and eventname = 'RECORD_STOP'";

        PreparedStatement preparedStatement = conn.prepareStatement(sql);

        ResultSet resultSet = preparedStatement.executeQuery();
        logger.info("获取语音数据成功");
        List<ZjRecord> zjRecords = new ArrayList<>();
        while (resultSet.next()) {
            ZjRecord zjRecord = new ZjRecord();
            zjRecord.setRecordId(resultSet.getString("recordId")); // 录音ID
            zjRecord.setRecordUuid(resultSet.getString("recordUuid")); // 录音UUID
            zjRecord.setAgentId(resultSet.getString("agentId")); // 坐席工号
            zjRecord.setAni(resultSet.getString("ani")); // 主叫号码
            zjRecord.setDnis(resultSet.getString("dnis")); // 被叫号码
            zjRecord.setRecordDir(resultSet.getString("recordDir")); // 录音地址
            zjRecord.setRecordFilepath(resultSet.getString("recordFilepath")); // 录音文件地址
            zjRecord.setRecordSeconds(resultSet.getString("recordSeconds")); // 通话时长（秒转化为  x分x秒）
            //录音开始时间

            zjRecord.setRecordStartTime(DateUtils.parseDate(resultSet.getString("startrecordtime")));
            //录音结束时间
            zjRecord.setRecordEndTime(DateUtils.parseDate(resultSet.getString("eventTime")));
            //录音开始时间
            zjRecord.setCreateTime(DateUtils.parseDate(resultSet.getString("startrecordtime"))); // 录音创建时间
            String callType = resultSet.getString("callDirection");
            if ("1".equals(callType)) zjRecord.setCallType("呼入");
            if ("0".equals(callType)) zjRecord.setCallType("拨出"); // 呼叫类型
            // 匹配工单号
            String wpid = iZjRecordService.getWpidByRecordId(zjRecord.getRecordUuid());
            zjRecord.setWpid(wpid);
            zjRecords.add(zjRecord);
        }
        // 插入理想的库
        if (zjRecords.size() > 0) {
            for (ZjRecord z : zjRecords) {
                iZjRecordService.insertZjRecord(z);
            }
        }
        logger.info("同步录音信息结束，共同步" + zjRecords.size() + "条录音数据");
        resultSet.close();
        preparedStatement.close();
        conn.close();
    }

    /**
     * 每5分钟执行一次
     */
    //@Scheduled(cron = "0 0/5 * * * ? ")
    public void checkAndSendSms() {
        if (!"8091".equals(port)) {
            return;
        }
        String jsonString = HttpClientUtils.get(checkSmsUrl, null);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        if (jsonObject == null) {
            throw new BaseException("检验分机接口连接超时！");
        }
        Integer count = jsonObject.getInteger("count");
        if (count == 0) {
            //代表分机全部掉线，需要发送短信
            tsmsSendLogService.sendSms();
        }

    }

    /**
     * 匹配工单编号
     */
    /*private String getWpid(ZjRecord zjRecord){
        // 如果是拨出根据被叫号码自动匹配近一年的工单，根据工单创建时间降序排列；
        // 如果是呼入根据主叫号码自动匹配近一年的工单，根据工单创建时间降序排列；如果是三方通话要展示拨出的用户号码
        String tel = null;
        if("呼入".equals(zjRecord.getCallType())){
            tel = zjRecord.getAni();
        }else if ("拨出".equals(zjRecord.getCallType())){
            tel = zjRecord.getDnis();
        }else {
            return null;
        }
        // 根据tel匹配工单
        return iZjRecordService.getWpidByTel(tel);
    }*/
}
